package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategory1Mapper baseCategory1Mapper;

	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper;

	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper;

	@Autowired
	private BaseCategoryViewMapper baseCategoryViewMapper;

	@Autowired
	private BaseAttributeMapper baseAttributeMapper;

    /*@Override
    public List<JSONObject> getBaseCategoryList() {
		//1.创建目标集合对象
		List<JSONObject> allList = new ArrayList<>();

		//2.查询分类视图得到所有分类数据 共计401条记录
		List<BaseCategoryView> allCategoryList = baseCategoryViewMapper.selectList(null);

		// 将所有类别按一级类别ID分组
		Map<Long, List<BaseCategoryView>> category1Map = allCategoryList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

		// 如果分组结果不为空，则进一步处理每个分组
		if(CollectionUtil.isNotEmpty(category1Map)) {
			for (Map.Entry<Long, List<BaseCategoryView>> entry1 : category1Map.entrySet()) {
				// 获取一级类别ID
				Long category1Id = entry1.getKey();
				// 获取该一级类别下的第一个类别的名称作为代表
				String category1Name = entry1.getValue().get(0).getCategory1Name();
				// 创建一个JSON对象来存储一级类别信息
				JSONObject jsonObject1 = new JSONObject();
				// 将一级类别ID存入JSON对象,// 将一级类别名称存入JSON对象
				jsonObject1.put("categoryId", category1Id);
				jsonObject1.put("categoryName", category1Name);
				// 将类别视图按category2Id分组
				Map<Long, List<BaseCategoryView>> category2Map = entry1.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
				// 如果category2Map不为空，则进一步处理
				if (CollectionUtil.isNotEmpty(category2Map)) {
					// 创建一个列表，用于存储第二级类别的JSON对象
					List<JSONObject> jsonObject2List = new ArrayList<>();
					// 遍历category2Map，处理每个第二级类别
					for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {
						// 获取当前第二级类别的ID
						Long category2Id = entry2.getKey();
						// 获取当前第二级类别的名称
						String category2Name = entry2.getValue().get(0).getCategory2Name();
						// 创建一个JSON对象，用于存储当前第二级类别的信息
						JSONObject jsonObject2 = new JSONObject();
						jsonObject2.put("categoryId", category2Id);
						jsonObject2.put("categoryName", category2Name);
						// 创建一个列表，用于存储当前第二级类别下的所有第三级类别的JSON对象
						List<JSONObject> jsonObject3List = new ArrayList<>();
						// 遍历当前第二级类别下的所有第三级类别，创建并添加到jsonObject3List中
						entry2.getValue().stream().forEach(baseCategoryView -> {
							JSONObject jsonObject3 = new JSONObject();
							jsonObject3.put("categoryId", baseCategoryView.getCategory3Id());
							jsonObject3.put("categoryName", baseCategoryView.getCategory3Name());
							jsonObject3List.add(jsonObject3);
						});
						// 将当前第二级类别下的所有第三级类别添加到jsonObject2中
						jsonObject2.put("categoryChild", jsonObject3List);
						// 将当前第二级类别的信息添加到jsonObject2List中
						jsonObject2List.add(jsonObject2);
					}
					// 将所有第二级类别的信息添加到jsonObject1中
					jsonObject1.put("categoryChild", jsonObject2List);
					// 将当前类别视图的信息添加到allList中
					allList.add(jsonObject1);
				}

			}
		}
		return allList;
	}*/

	@Override
	@GuiGuCache(prefix = "baseCategoryList:")
	public List<JSONObject> getBaseCategoryList() {
		// 查询所有分类数据
		List<BaseCategoryView> allCategoryList = baseCategoryViewMapper.selectList(null);

		// 按一级分类ID分组，并构建一级分类节点
		return allCategoryList.stream()
				.collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id))
				.entrySet().stream()
				.map(entry1 -> {
					Long category1Id = entry1.getKey();
					String category1Name = entry1.getValue().get(0).getCategory1Name();

					JSONObject category1Node = createCategoryNode(category1Id, category1Name);

					// 按二级分类ID分组，并构建二级分类节点列表
					List<JSONObject> category2Nodes = entry1.getValue().stream()
							.collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id))
							.entrySet().stream()
							.map(entry2 -> {
								Long category2Id = entry2.getKey();
								String category2Name = entry2.getValue().get(0).getCategory2Name();

								JSONObject category2Node = createCategoryNode(category2Id, category2Name);

								// 构建三级分类节点列表
								List<JSONObject> category3Nodes = entry2.getValue().stream()
										.map(view -> createCategoryNode(view.getCategory3Id(), view.getCategory3Name()))
										.collect(Collectors.toList());

								category2Node.put("categoryChild", category3Nodes);
								return category2Node;
							})
							.collect(Collectors.toList());

					category1Node.put("categoryChild", category2Nodes);
					return category1Node;
				})
				.collect(Collectors.toList());
	}

	/**
	 * 创建分类节点的通用方法
	 */
	private JSONObject createCategoryNode(Long categoryId, String categoryName) {
		JSONObject node = new JSONObject();
		node.put("categoryId", categoryId);
		node.put("categoryName", categoryName);
		return node;
	}

	@Override
	@GuiGuCache(prefix = "category1Id:attributes:")
	public List<BaseAttribute> getAttributesByCategory1Id(Long category1Id) {
		//调用持久层动态SQL完成一对多查询
		return baseAttributeMapper.selectAttributesByCategory1Id(category1Id);
	}

	/**
	 * 根据三级分类Id 获取到分类信息
	 * @param category3Id
	 * @return
	 */
	@Override
	@GuiGuCache(prefix = "category3View:")
	public BaseCategoryView getCategoryView(Long category3Id) {
		return baseCategoryViewMapper.selectCategoryView(category3Id);
	}

	/**
	 * 根据一级分类Id查询三级分类列表
	 * @param category1Id
	 * @return
	 */
    @Override
	@GuiGuCache(prefix = "baseCategory3Top7:")
    public List<BaseCategory3> getTop7BaseCategory3(Long category1Id) {
		//根据一级分类ID查询二级分类集合，得到二级分类ID集合
		LambdaQueryWrapper<BaseCategory2> BaseCategory2QueryWrapper = new LambdaQueryWrapper<>();
		BaseCategory2QueryWrapper.eq(BaseCategory2::getCategory1Id, category1Id);
		BaseCategory2QueryWrapper.select(BaseCategory2::getId);

		//获取二级分类ID集合
		List<BaseCategory2> category2List = baseCategory2Mapper.selectList(BaseCategory2QueryWrapper);
		List<Long> category2IdList = category2List.stream().map(baseCategory2 -> baseCategory2.getId()).collect(Collectors.toList());

		LambdaQueryWrapper<BaseCategory3> BaseCategory3QueryWrapper = new LambdaQueryWrapper<>();
		//查询二级分类下包含三级分类
		BaseCategory3QueryWrapper.in(BaseCategory3::getCategory2Id, category2IdList);
		//查询需要置顶的三级分类
		BaseCategory3QueryWrapper.eq(BaseCategory3::getIsTop, 1);
		//根据序号排序 升序排
		BaseCategory3QueryWrapper.orderByAsc(BaseCategory3::getOrderNum);
		//截取前7个 SQL+limit 7
		BaseCategory3QueryWrapper.last("limit 7");
		return baseCategory3Mapper.selectList(BaseCategory3QueryWrapper);
    }

	/**
	 * 根据一级分类id获取全部分类信息
	 * @param category1Id
	 * @return
	 */
	@Override
	public JSONObject getBaseCategoryList(Long baseCategory1Id) {
		// 查询所有分类数据
		List<BaseCategoryView> baseCategory1List = baseCategoryViewMapper.selectList(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory1Id, baseCategory1Id));

		// 按一级分类ID分组，并构建一级分类节点
		if (CollectionUtil.isNotEmpty(baseCategory1List)){
			JSONObject category1Node = createCategoryNode(baseCategory1List.get(0).getCategory1Id(), baseCategory1List.get(0).getCategory1Name());
			// 按二级分类ID分组，并构建二级分类节点列表
			List<JSONObject> category2Nodes = baseCategory1List.stream()
					.collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id))
					.entrySet().stream()
					.map(entry2 -> {
						Long category2Id = entry2.getKey();
						String category2Name = entry2.getValue().get(0).getCategory2Name();

						JSONObject category2Node = createCategoryNode(category2Id, category2Name);

						// 构建三级分类节点列表
						List<JSONObject> category3Nodes = entry2.getValue().stream()
								.map(view -> createCategoryNode(view.getCategory3Id(), view.getCategory3Name()))
								.collect(Collectors.toList());

						category2Node.put("categoryChild", category3Nodes);
						return category2Node;
					})
					.collect(Collectors.toList());

			category1Node.put("categoryChild", category2Nodes);
			return category1Node;
		}
		return null;
	}

}
